/**
 * Created by seth.yang on 2016/9/14
 */
(function ($) {
    if ($.fn.foldablePanel) return;
    function open () {
        var panel   = $(this),
            button  = panel.data ('button'),
            options = panel.data ('options'),
            flag    = panel.attr ('data-opened');
        if (!button || flag) return;

        panel.attr ('data-opened', true).show ().animate ({height:panel[0].scrollHeight}, 'quick', function () {
            button.addClass ('icon-button-up').removeClass ('icon-button-down');
            panel.css ('height', '');
            if ('opened' in options) {
                call (panel, options['opened']);
            }
        });
    }

    function close () {
        var panel   = $(this),
            button  = panel.data ('button'),
            options = panel.data ('options'),
            flag    = panel.attr ('data-opened');
        if (!button || !flag) return;

        panel.removeAttr ('data-opened').animate ({height:options.minHeight}, 'quick', function () {
            //self.text ('»');
            button.removeClass ('icon-button-up').addClass ('icon-button-down');
            if ('closed' in options) {
                call (panel, options['closed']);
            }
            if (options.minHeight == 0) {
                panel.hide ();
            }
        });
    }

    $.fn.foldablePanel = function (options) {
        options = options || {minHeight: 20};
        return this.each (function () {
            var self = $(this),
                target = $('#' + self.attr ('data-for')).attr ('data-opened', true);
            if (target && target.length) {
                target.data ('button', self).data ('options', options);
                self.on ('click', function () {
                    if (self.hasClass ('icon-button-down')) {
                        target.open ();
                    } else {
                        target.close ();
                    }
                });
                $.fn.open = open;
                $.fn.close = close;

                target.close ();
            }
        });
    };
})(jQuery);